/**
 * Copyright (C) 2012 Neofonie GmbH
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.dicodeproject.analysis.pig;

import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.Tuple;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Transforms a bag of tuples into a JSON string:
 * {(a,1),(b,2),(c,3)}
 * -->
 * {"result":[{"a":1},{"b":2},{"c":3}]}
 */
public class ResultToJson extends EvalFunc<String> {

    @Override
    public String exec(Tuple input) throws IOException {
        JSONObject result = new JSONObject();
        try {

            JSONArray list = new JSONArray();
            DataBag bag = (DataBag) input.get(0);
            for (Tuple tuple : bag) {
                if (tuple == null || tuple.size() < 3) {
                    continue;
                }
                String field = (String) tuple.get(1);
                Long count = (Long) tuple.get(2);
                if (field == null || count == null) {
                    continue;
                }
                Map<String, Long> keyVal = new HashMap<String, Long>(1);
                keyVal.put(field, count);
                list.put(keyVal);
            }
            result.put("result", list);

        } catch (JSONException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        return result.toString();
    }

}
